package com.ruoyi.web.controller.device.keep;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Report;
import com.ruoyi.common.core.domain.entity.ReportSubscript;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SmsTemplateCode;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SmsUtils;
import com.ruoyi.system.mapper.ReportMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ReportRecordService;
import com.ruoyi.system.service.ReportService;
import com.ruoyi.system.service.resp.EnergyRecordAreaResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Api("住户上报维修")
@RestController
@RequestMapping("/device/keep/report")
public class ReportController extends BaseController {
    @Autowired
    private ReportService reportService;

    @Resource
    private ReportMapper reportMapper;

    @Resource
    private ReportRecordService reportRecordService;

    @Resource
    private SysUserMapper sysUserMapper;

    private Date shierBegin = new Date(1701360000000L);

    @GetMapping("/listtaiyangdaoShiyi")
    public AjaxResult listtaiyangdaoShiyi() {
        return AjaxResult.success(reportMapper.counttaiyangdaoshiyi(shierBegin));
    }

    @GetMapping("/listtaiyangdaoShier")
    public AjaxResult listtaiyangdaoShier() {
        return AjaxResult.success(reportMapper.counttaiyangdaoshier(shierBegin));
    }

    @GetMapping("/listyihaoyuanShiyi")
    public AjaxResult listyihaoyuanShiyi() {
        return AjaxResult.success(reportMapper.countyihaoyuanshiyi(shierBegin));
    }

    @GetMapping("/listyihaoyuanShier")
    public AjaxResult listyihaoyuanShier() {
        return AjaxResult.success(reportMapper.countyihaoyuanshier(shierBegin));
    }

    @ApiOperation("分页查询住户申报")
    @Log(title = "查询住户申报", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(Report report) {
        startPage();
        List<Report> list = reportMapper.selectCustomerReportList(report);
        fillInfo(list);
        return getDataTable(list);
    }

    private void fillInfo(List<Report> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<SysUser> sysUsers = sysUserMapper.selectUserByUserIds(list.stream().map(Report::getCustomerId).toArray(Long[]::new));
        Map<Long, SysUser> sysUserMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId, s -> s));

        List<SysUser> sysUsers1 = sysUserMapper.selectUserByUserIds(list.stream().map(Report::getKeeperId).toArray(Long[]::new));
        Map<Long, SysUser> sysUserMap1 = sysUsers1.stream().collect(Collectors.toMap(SysUser::getUserId, s -> s));
        list.forEach(r -> {
            r.setCustomerName(Optional.ofNullable(sysUserMap.get(r.getCustomerId())).map(SysUser::getNickName).orElse(null));
            r.setKeeperName(Optional.ofNullable(sysUserMap1.get(r.getKeeperId())).map(SysUser::getNickName).orElse(null));
        });
    }

    @ApiOperation("分页查询设备维护")
    @Log(title = "查询设备维护", businessType = BusinessType.OTHER)
    @GetMapping("/listDevice")
    public TableDataInfo listDevice(Report report) {
        startPage();
        List<Report> list = reportMapper.selectDeviceReportList(report);
        fillInfo(list);
        return getDataTable(list);
    }

    @ApiOperation("分页查询待我维修")
    @Log(title = "查询待我维修", businessType = BusinessType.OTHER)
    @GetMapping("/listNeedMe")
    public TableDataInfo listNeedMe() {
        startPage();
        List<Report> list = reportService.selectNeedMeCustomerList(SecurityUtils.getUserId());
        fillInfo(list);
        return getDataTable(list);
    }

    @ApiOperation("获取待我维修、维修管理角标")
    @Log(title = "查询待我维修", businessType = BusinessType.OTHER)
    @GetMapping("/getReportSubscript")
    public AjaxResult getReportSubscript(Report query) {
        Report report1 = new Report();
        report1.setStatus("待接收");
        if (query != null && query.getKeeperId() != null) {
            report1.setKeeperId(query.getKeeperId());
        }
//        List<Report> list = reportMapper.selectList(report1);

        Report report2 = new Report();
        report2.setCustomerId(SecurityUtils.getUserId());
        List<Report> list = reportService.selectNotFinishedReportList(report2);
        Report report = new Report();
        report.setStatus("待指派");
        List<Report> all = reportMapper.selectList(report);
        List<ReportSubscript> reportSubscripts = new ArrayList<>();
        ReportSubscript reportSubscript = new ReportSubscript();
        reportSubscript.setItem("me");
        reportSubscript.setTotal(CollectionUtils.isEmpty(list) ? 0 : list.size());
        reportSubscripts.add(reportSubscript);

        ReportSubscript reportSubscript1 = new ReportSubscript();
        reportSubscript1.setItem("all");
        reportSubscript1.setTotal(CollectionUtils.isEmpty(all) ? 0 : all.size());
        reportSubscripts.add(reportSubscript1);
        return AjaxResult.success(reportSubscripts);
    }

    @ApiOperation("分页查询我已维修")
    @Log(title = "查询我已维修", businessType = BusinessType.OTHER)
    @GetMapping("/listMyFinished")
    public TableDataInfo listMyFinished(Report report) {
        startPage();
        List<Report> list = reportService.selectReportList(report);
        fillInfo(list);
        return getDataTable(list);
    }

    @ApiOperation("分页查询住户未完成申报")
    @Log(title = "查询住户未完成申报", businessType = BusinessType.OTHER)
    @GetMapping("/listNotFinished")
    public TableDataInfo listNotFinished(Report report) {
        startPage();
        report.setCustomerId(SecurityUtils.getUserId());
        List<Report> list = reportService.selectNotFinishedReportList(report);
        fillInfo(list);
        return getDataTable(list);
    }

    @ApiOperation("查询住户所有申报")
    @Log(title = "查询住户申报All", businessType = BusinessType.OTHER)
    @GetMapping("/listAll")
    public TableDataInfo listAll(Report report) {
        List<Report> list = reportService.selectAll(report);
        fillInfo(list);
        return getDataTable(list);
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        Report report = reportService.selectById(id);
        if (report.getKeeperId() != null) {
            SysUser sysUser = sysUserMapper.selectUserById(report.getKeeperId());
            report.setKeeperName(Optional.ofNullable(sysUser).map(SysUser::getNickName).orElse(null));
        }
        if (report.getCustomerId() != null) {
            SysUser sysUser = sysUserMapper.selectUserById(report.getCustomerId());
            report.setCustomerName(Optional.ofNullable(sysUser).map(SysUser::getNickName).orElse(null));
        }
        return success(report);
    }

    @ApiOperation("新增住户申报")
    @Log(title = "新增住户申报", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody Report report) {
        report.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        report.setCustomerId(SecurityUtils.getUserId());
        Boolean result = reportService.createKeep(report);
        //给运维科正副科长发送短信
        try {
            List<String> phones = sysUserMapper.getSmsPhones();
            for (String phone : phones) {
                SmsUtils.sendSms(SmsTemplateCode.OK.getCode(), phone, "");
            }
        } catch (Exception e) {

        }
        if (result) {
            return success();
        }
        return error();
    }

    @ApiOperation("修改住户申报")
    @Log(title = "修改住户申报", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@Validated @RequestBody Report report) {
        report.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = reportService.updateReport(report);
        //给被指派的人发送短信
        try {
            if (report.getKeeperId() == null) {
                throw new BaseException("指派失败,指派人为空");
            }
            SysUser sysUser = sysUserMapper.selectUserById(report.getKeeperId());
            if (sysUser == null) {
                throw new BaseException("指派失败,未查询到指派人" + report.getKeeperId());
            }
            if (com.ruoyi.common.utils.StringUtils.isNotBlank(sysUser.getPhonenumber())) {
                SmsUtils.sendSms(SmsTemplateCode.DELETED.getCode(), sysUser.getPhonenumber(), "");
            }
        } catch (Exception e) {

        }
        if (result) {
            return success();
        }
        return error();
    }

    @ApiOperation("删除住户申报")
    @Log(title = "删除住户申报", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(reportService.deleteById(id));
    }


    @GetMapping("/oneData")
    public AjaxResult oneData(EnergyRecordAreaResp resp) {
        resp.setTimeSeries(getZHTimeSeries());
        resp.setDataReport(getOneData(getZHTimeSeries(), "一区", resp));
        return success(resp);
    }

    @GetMapping("/TwoData")
    public AjaxResult TwoData(EnergyRecordAreaResp resp) {
        resp.setTimeSeries(getZHTimeSeries());
        resp.setDataReport(getOneData(getZHTimeSeries(), "二区", resp));
        return success(resp);
    }

    private List<String> getZHTimeSeries() {
        List<String> result = new ArrayList<>();
        for (int i = 1; i < 13; i++) {
            result.add(i + "月");
        }
        return result;
    }

    private List<Integer> getOneData(List<String> timeSeries, String location, EnergyRecordAreaResp resp) {
        List<Integer> one = new ArrayList<>();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String year = "";
        if (resp != null && StringUtils.isNotBlank(resp.getSearchDate())) {
            year = resp.getSearchDate();
        }

        for (String timeSery : timeSeries) {
            timeSery = timeSery.replace("月", "");
            Calendar calendar = Calendar.getInstance();
            if (StringUtils.isBlank(year)) {
                int i = calendar.get(Calendar.YEAR);
                year = i + "";
            }
            calendar.set(Integer.parseInt(year), Integer.parseInt(timeSery) - 1, 1); // 设置年份和月份
            int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 获取该月的最大天数
            String startTime = year + "-" + timeSery + "-01 00:00:00";
            String endTime = year + "-" + timeSery + "-" + lastDay + " 23:59:59";
            Integer amountByArea = reportService.selectListCount(startTime, endTime, location);
            one.add(amountByArea == null ? 0 : amountByArea);
        }
        return one;
    }


}
